package com.example.demo.controller;

import com.example.demo.conmon.BaseController;
import com.example.demo.conmon.R;
import com.example.demo.entity.Account;
import com.example.demo.mapper.AccountMapper;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;


    @GetMapping("/list")
    public R<List<Account>> index() {
        log.info("------------->哈哈哈哈哈哈");

        if (true){
//            throw new ServiceException("没有权限访问用户数据！");
            double a = 10/0;
        }
        return R.ok(accountMapper.selectAll());
    }

    /***
     * MethodsDescription
     * 动态数据源切换
     \
     * @return com.example.demo.conmon.R<java.util.List<com.example.demo.entity.Account>>
     * @author ljl
     * @date 2025/7/29 22:45
     * @version v1.0
     */
    @PostMapping("/selectOneByQuery")
    public R<List<Account>> selectOneByQuery(@RequestBody Account account) {

        // 动态切换数据源
        System.out.println("------------->"+DataSourceKey.get());
        List<Account> accountList = new ArrayList<>();
        try {
            DataSourceKey.use("db2");
            System.out.println("------------->"+DataSourceKey.get());
            accountList = accountMapper.selectListWithRelationsByQuery(QueryWrapper.create(account));

            DataSourceKey.use("db1");
            System.out.println("------------->"+DataSourceKey.get());
            accountList = accountMapper.selectListWithRelationsByQuery(QueryWrapper.create(account));
        }finally {
            DataSourceKey.clear();
        }
       return R.ok(accountList);
    }

    /***
     * MethodsDescription
     * 测试线程池
     * @return void
     * @author ljl
     * @date 2025/7/29 22:45
     * @version v1.0
     */
    @GetMapping("/exec")
    public void exec() {
        threadPoolExecutor.execute(() -> log.info("test"));
    }



    @GetMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> save() {
        Account account2 = new Account();
        account2.setUserName("用户");
        account2.setAge(1);
        account2.setBirthday(new Date());
        return toAjax(accountMapper.insert(account2));
    }
}
